<template>
	<div class="video w944">
		<alert ref="alert"></alert>
		<div class="label_top">
			<button @click="cancel"><i><&nbsp;</i>返回</button>
			<p>{{updateTitle}}</p>
		</div>
		<div class="videoLine">
			<span class="tit">视频名称：</span>
			<input type="text" v-model="name"/>
		</div>
		<div class="videoLine heiT">
			<span class="tit">上传视频：</span>
			<a class="uploadVideoBtn"><input type="file" id="fileUpload" @change="fileChange($event)">选择文件</a>
			<button @click="authUpload" :disabled="uploadDisabled">开始上传</button>
			<span class="progress">上传进度: <i id="auth-progress">{{authProgress}}</i>%</span>
			<em>目前视频上传只支持MP4格式</em>
		</div>
		<div class="videoLine">
			<span class="tit">视频介绍：</span>
			<vue-ueditor-wrap v-model="coursewareVideoDes" :config="myConfig" style="margin: 14px 0 0 85px;"></vue-ueditor-wrap>
		</div>
		<div class="footerButton">
			<a @click="checkSave" v-bind:style="{background: clickLock==true ? '#44CEF6' : '#3a8ee6'}">保存</a>
			<a @click="cancel" class="cancel">取消</a>
		</div>
	</div>
</template>

<script>
	import axios from 'axios';
	import alert from '../../components/Alert.vue';
	export default{
		data(){
			return{
				clickLock:true,
				updateTitle:'添加视频',
				updateTitleCourse:'',
				teacherTitle:'',
				lecturerid:'',
				nowType:'add',
				liveId:'',
				id:'',
				name:'',
				coursewareAliyunVideoId:'',
				coursewareVideoDes:'',
				coursewareVideoIsBm:'',
				coursewareVideoIsBx:'',
				myConfig: {
					autoHeightEnabled: false,
					initialFrameHeight: 420,
					initialFrameWidth: '840'
				},
				
				timeout: '60000',
				partSize: '1048576',
				parallel: '5',
				retryCount: '3',
				retryDuration: '2',
				region: 'cn-shanghai',
				userId: '1585664211304336', //1303984639806000
				file: null,
				authProgress: 0,
				uploadDisabled: true,
				resumeDisabled: true,
				pauseDisabled: true,
				uploader: null,
			}
		},
		methods:{
			getParams() {
				var routerParams = this.$route.params.type;
				this.liveId = this.$route.params.liveId;
				this.updateTitleCourse = this.$route.params.updateTitleCourse;
				this.pathKey = this.$route.params.pathKey;
				this.teacherTitle = this.$route.params.teacherTitle;
				this.lecturerid = this.$route.params.lecturerid;
				if(routerParams == 'edit') {
					this.nowType = 'edit';
					this.updateTitle = "编辑视频";
				} else {
					this.nowType = 'add';
				}
				console.log('video:',this.$route.params);
			},
			add_type(){
				let that = this;
				let s= {
					courseid:that.liveId,
					name:that.name,
					coursewareAliyunVideoId:that.coursewareAliyunVideoId,
					coursewareVideoDes:that.coursewareVideoDes,
					coursewareVideoIsBm:0,
					coursewareVideoIsBx:0,
					rootcompanyid:1
				};
				if(this.clickLock==true){
					this.clickLock = false;
					this.$ajax({
						url: this.$root.jifuUrl + '/mns/coursewareVideo/addCoursewareVideo',
						headers:{'ContentType': 'application/json; charset=utf-8'},
						data: s,					
						method: 'POST',
						success: res => {
							if(res.data.code == 200) {
								this.$refs.alert.show({alertText: '保存成功'});
								setTimeout(() =>{
									this.$router.push({
										name: 'courseware',
										params: {
											liveId:this.liveId,
											updateTitle:this.updateTitleCourse,
											pathKey:this.pathKey,
											teacherTitle:this.teacherTitle,
											lecturerid:this.lecturerid
										}
									})
								},2000)
							}else{
								this.clickLock = true;
								this.failText = res.data.message;
								this.$rootFunction().deleteResFail();
							}
						}
					});
				}
			},
			edit_type(){
				let that = this;
				let s= {
					id:that.id,
					courseid:that.liveId,
					name:that.name,
					coursewareAliyunVideoId:that.coursewareAliyunVideoId,
					coursewareVideoDes:that.coursewareVideoDes,
					coursewareVideoIsBm:0,
					coursewareVideoIsBx:0,
					rootcompanyid:1
				};
				this.$ajax({
					url: this.$root.jifuUrl + '/mns/coursewareVideo/updateCoursewareVideo',
					headers:{'ContentType': 'application/json; charset=utf-8'},
					data: s,					
					method: 'POST',
					success: res => {
						if(res.data.code == 200) {
							this.$refs.alert.show({alertText: '保存成功'});
							setTimeout(() =>{
								this.$router.push({
									name: 'courseware',
									params: {
										liveId:this.liveId,
										updateTitle:this.updateTitleCourse,
										pathKey:this.pathKey,
										teacherTitle:this.teacherTitle,
										lecturerid:this.lecturerid
									}
								})
							},2000)
						}else{
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
					}
				});
			},
			checkSave(){
				let that = this;
				if(that.nowType == 'add'){
					that.add_type();
				}else if(that.nowType == 'edit'){
					this.edit_type();
				}
			},
			cancel() {
				this.$router.push({
					name: 'courseware',
					params: {
						liveId:this.liveId,
						updateTitle:this.updateTitleCourse,
						pathKey:this.pathKey,
						teacherTitle:this.teacherTitle,
						lecturerid:this.lecturerid
					}
				})
			},
			fileChange(e) {
				this.file = e.target.files[0];
				if(!this.file) {
					alert("请先选择需要上传的文件!")
					return
				}
				var Title = this.file.name
				var userData = '{"Vod":{}}'
				if(this.uploader) {
					this.uploader.stopUpload()
					this.authProgress = 0
					this.statusText = ""
				}
				this.uploader = this.createUploader()
				//console.log(userData)
				this.uploader.addFile(this.file, null, null, null, userData)
				this.uploadDisabled = false
				this.pauseDisabled = true
				this.resumeDisabled = true
			},
			authUpload() {
				// 然后调用 startUpload 方法, 开始上传
				if(this.uploader !== null) {
					this.uploader.startUpload()
					this.uploadDisabled = true
					this.pauseDisabled = false
				}
			},
			// 暂停上传
			pauseUpload() {
				if(this.uploader !== null) {
					this.uploader.stopUpload()
					this.resumeDisabled = false
					this.pauseDisabled = true
				}
			},
			// 恢复上传
			resumeUpload() {
				if(this.uploader !== null) {
					this.uploader.startUpload()
					this.resumeDisabled = true
					this.pauseDisabled = false
				}
			},
			createUploader(type) {
				let self = this
				let uploader = new AliyunUpload.Vod({
					timeout: self.timeout || 60000,
					partSize: self.partSize || 1048576,
					parallel: self.parallel || 5,
					retryCount: self.retryCount || 3,
					retryDuration: self.retryDuration || 2,
					region: self.region,
					userId: self.userId,
					// 添加文件成功
					addFileSuccess: function(uploadInfo) {
						self.uploadDisabled = false
						self.resumeDisabled = false
						self.statusText = '添加文件成功, 等待上传...'
					},
					// 开始上传
					onUploadstarted: function(uploadInfo) {
						if(!uploadInfo.videoId) {
							let createUrl = 'http://www.h3clearning.com/huathree-back/uploadV?Title=' + uploadInfo.file.name;
							axios.get(createUrl).then(({data}) => {
								let uploadAuth = data.data.UploadAuth
								let uploadAddress = data.data.UploadAddress
								let videoId = data.data.VideoId
								uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
							})
							self.statusText = '文件开始上传...'
							console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
						} else {
							let refreshUrl = 'http://www.h3clearning.com/huathree-back/uploadV?Title=' + uploadInfo.videoId;
							axios.get(refreshUrl).then(({data}) => {
								let uploadAuth = data.data.UploadAuth
								let uploadAddress = data.data.UploadAddress
								let videoId = data.data.VideoId
								uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
							})
						}
					},
					// 文件上传成功
					onUploadSucceed: function(uploadInfo) {
						console.log("-------->"+uploadInfo+"onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
						console.log('++++++++++++++++++'+uploadInfo.videoId);
						self.statusText = '文件上传成功!';
						self.coursewareAliyunVideoId= uploadInfo.videoId;
					},
					// 文件上传失败
					onUploadFailed: function(uploadInfo, code, message) {
						self.statusText = '文件上传失败!'
					},
					// 取消文件上传
					onUploadCanceled: function(uploadInfo, code, message) {
						self.statusText = '文件已暂停上传'
					},
					// 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
					onUploadProgress: function(uploadInfo, totalSize, progress) {
//						console.log("onUploadProgress:file:" +  this.updateVideoTitle + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
						let progressPercent = Math.ceil(progress * 100)
						self.authProgress = progressPercent
						self.statusText = '文件上传中...'
					},
					// 上传凭证超时
					onUploadTokenExpired: function(uploadInfo) {
						let refreshUrl = 'http://www.h3clearning.com/huathree-back/refreshVideo?VideoId=' + uploadInfo.videoId;
						axios.get(refreshUrl).then(({data}) => {
							let uploadAuth = data.data.UploadAuth
							uploader.resumeUploadWithAuth(uploadAuth)
						})
						self.statusText = '文件超时...'
					},
					// 全部文件上传结束
					onUploadEnd: function(uploadInfo) {
						self.statusText = '文件上传完毕'
					}
				}) 
				return uploader;
			}
		},
		components:{
			alert
		},
		mounted(){
			this.getParams();
			if(this.liveId==null){
				this.$store.commit('GET_video');
				var s =this.$store.state.video;
				this.liveId=s.liveId;
				this.updateTitleCourse = s.updateTitleCourse;
				this.pathKey = s.pathKey;
				this.teacherTitle = s.teacherTitle;
				this.lecturerid = s.lecturerid;
			};
			window.addEventListener("beforeunload",()=>{
				s={
					liveId : this.liveId,
					updateTitleCourse:this.updateTitleCourse,
					pathKey:this.pathKey,
					teacherTitle:this.teacherTitle,
					lecturerid:this.lecturerid
				}	
				this.$store.commit('SET_video', s);
			});
			if(this.nowType=="edit"){
				console.log('视频--306',this.nowType,this.$root.videoMsg);
				this.id = this.$root.videoMsg.id;
				this.courseid = this.$root.videoMsg.courseid;
				this.name = this.$root.videoMsg.name;
				this.coursewareAliyunVideoId = this.$root.videoMsg.coursewareAliyunVideoId;
				this.coursewareVideoDes = this.$root.videoMsg.coursewareVideoDes;
				this.coursewareVideoIsBm = this.$root.videoMsg.coursewareVideoIsBm;
				this.coursewareVideoIsBx = this.$root.videoMsg.coursewareVideoIsBx;
				this.rootcompanyid = this.$root.videoMsg.rootcompanyid;
				this.authProgress = 100
			}
		}
	}
</script>

<style>
	.videoLine{margin-bottom: 20px;position: relative;}
	.videoLine.heiT{height: 60px;}
	.videoLine span{color: #333;}
	.videoLine .tit{font-size: 16px;color: #333;width: 80px;text-align: right;display: inline-block;}
	.videoLine input{width: 200px;height: 30px;line-height:30px;border: 1px solid #ccc;padding-left: 10px;color: #666;font-size: 14px;border-radius: 5px;}
	.videoLine.heiT .el-radio{display: block;margin-bottom: 5px;}
	.videoLine .videoR{position: absolute;top: 0;left: 84px;}
	.videoLine em{display: block;font-size: 14px;color: #999;font-style: normal;margin: 11px 0 0 83px;}
	.videoLine .el-select,.videoLine .el-select input{width: 212px;height: 32px;line-height: 32px;}
	.videoLine .el-select .el-select__caret{height: 32px;line-height: 32px;}
	
	.videoLine .uploadVideoBtn{background:#44cef6;height:33px;line-height:33px;width:80px;display:inline-block;color:#fff;text-align: center;border-radius: 5px;cursor: pointer;outline: none;border: none;position: relative; *display: inline;font-size: 14px;}
	.videoLine .uploadVideoBtn input{height:33px;line-height:33px;width:80px;position: absolute;font-size: 80px;right: 0;top: 0;opacity: 0;filter: alpha(opacity=0);cursor: pointer;overflow: hidden;}
</style>